package com.lej.core.utils.extention

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.os.Build
import android.os.Bundle
import androidx.annotation.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.lej.core.base.app
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.collections.set


fun Activity.showLoading(tips: String? = null) {
    showTip(QMUITipDialog.Builder.ICON_TYPE_LOADING, tips)
}

fun FragmentActivity.addFragment(
    @IdRes containerViewId: Int,
    @NonNull fragment: Fragment,
    tag:String = "",
    builder: Bundle.() -> Unit = {}
) {
    fragment.arguments = Bundle().apply(builder)
    supportFragmentManager.beginTransaction()
        .add(containerViewId, fragment,tag).commit()
}

fun FragmentActivity.removeFragment(
    tag:String = "",
) {
    supportFragmentManager.findFragmentByTag(tag)
        ?.let {
            supportFragmentManager.beginTransaction().remove(it).commit()
        }
}

fun Activity.showMessage(
    tips: String? = null, timeout: Long = 1500,
    dissCallBack: ((Dialog) -> Unit)? = null
) {
    showTip(QMUITipDialog.Builder.ICON_TYPE_INFO, tips, timeout, dissCallBack)
}

fun Activity.showSuccess(
    tips: String? = null, timeout: Long = 1500,
    dissCallBack: ((Dialog) -> Unit)? = null
) {
    showTip(QMUITipDialog.Builder.ICON_TYPE_SUCCESS, tips, timeout, dissCallBack)
}

@Synchronized
fun Activity.showTip(
    iconType: Int,
    tips: String? = null,
    timeout: Long = 0,
    dissCallBack: ((Dialog) -> Unit)? = null
) {
    (this as? AppCompatActivity)?.apply {
        runOnUiThread {
            tipDialogMap[this.hashCode()]?.dismiss()
            tipDialogMap.remove(this.hashCode())

            val tipDialog = QMUITipDialog.Builder(this)
                .setIconType(iconType)
                .setTipWord(tips)
                .create()
            tipDialog?.show()
            val scope = MainScope()
            if (timeout > 0) {
                scope.launch {
                    delay(timeout)
                    tipDialog.dismiss()
                }
            }
            tipDialogMap[this.hashCode()] = tipDialog
            val activityHashCode = this.hashCode()
            tipDialog.setOnDismissListener {
                dissCallBack?.invoke(tipDialog)
                if (tipDialogMap[activityHashCode] == tipDialog) tipDialogMap.remove(
                    activityHashCode
                )
            }
            lifecycle.addObserver(object : DefaultLifecycleObserver {
                override fun onDestroy(owner: LifecycleOwner) {
                    scope.cancel()
                    tipDialogMap.remove(activityHashCode)
                }
            })
        }
    }
}

/**一个Activity 只有一个状态dialog 存在。需要谨慎看看有没有内存泄漏问题*/
val tipDialogMap = HashMap<Int, Dialog>()

fun Activity.disDialog() {
    runOnUiThread {
        tipDialogMap[this.hashCode()]?.dismiss()
        tipDialogMap.remove(this.hashCode())
    }
}

val Int.resColor: Int @ColorInt get() = app.getColorCompat(this)
val Int.resString: String get() = app.getString(this)
fun Context.getColorCompat(@ColorRes color: Int) = ContextCompat.getColor(this, color)
fun Context.getDrawableCompat(@DrawableRes drawableRes: Int) =
    ContextCompat.getDrawable(this, drawableRes)

@Suppress("DEPRECATION")
val Context.versionCode: Long
    get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        packageInfo.longVersionCode
    } else {
        packageInfo.versionCode.toLong()
    }

val Context.packageInfo get() = packageManager.getPackageInfo(packageName, 0)
val Context.versionName get() = packageInfo.versionName